﻿Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data.SqlClient
Imports System.Globalization
Imports System.Web.Script.Serialization
Imports System.Linq
Imports System.Data
Imports AjaxControlToolkit
Imports System.Collections.Generic
Imports CodeMatrix.Context
Imports CodeMatrix.Entities


' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService

    <WebMethod(EnableSession:=True)> _
    Function SaveData(ByVal jData As String) As String


        Dim json As JavaScriptSerializer = New JavaScriptSerializer()
        Dim cData = json.Deserialize(Of AuthenticationObject())(jData)
        Dim cmd As String = String.Empty
        Dim staff = ProfileCommon.Properties("staff_code")
        Using ctx As New DataClassesDataContext
            For Each i As AuthenticationObject In cData

                ' ========================================================================================
                ' Delete old data
                ' ========================================================================================
                ctx.stp_auth_departments.DeleteAllOnSubmit(From x In ctx.stp_auth_departments _
                                                           Where i.department_code = x.department_code _
                                                           Select x)


                ' ========================================================================================
                ' Insert authen department
                ' - Insert data when ava_department_code is true.
                ' ========================================================================================

                If i.ava_department_code Then

                    Dim dept = New CodeMatrix.Entities.stp_auth_department
                    dept.department_code = i.department_code
                    dept.sub_menu_code = i.sub_menu_code
                    dept.auth_department_status = 1
                    dept.staff_code_create = Convert.ToInt32(staff.DefaultValue)
                    dept.create_datetime = Now
                    dept.staff_code_update = Convert.ToInt32(staff.DefaultValue)
                    dept.update_datetime = Now

                    ctx.stp_auth_departments.InsertOnSubmit(dept)

                End If


            Next

            ' ========================================================================================
            ' Log data
            ' ========================================================================================
            cmd = CType(ctx.GetCommand(ctx.stp_auth_departments), SqlCommand).CommandText
            Dim log = New CodeMatrix.Entities.log_system()
            log.create_datetime = Now
            'log.log_code = 13
            log.log_description = cmd
            log.log_menu = 13
            log.log_type = "A"
            log.staff_code_create = Convert.ToInt32(staff.DefaultValue)
            log.staff_ip_address = HttpContext.Current.Request.UserHostAddress
            ctx.log_systems.InsertOnSubmit(log)


            ctx.SubmitChanges()

        End Using




        Return 0
    End Function


    <WebMethod(EnableSession:=True)> _
    Function GetDepartmentHirachy() As CascadingDropDownNameValue()

        Dim cCascadingDropDownNameValue As List(Of CascadingDropDownNameValue)
        cCascadingDropDownNameValue = New List(Of CascadingDropDownNameValue)
        Dim tbl As DataTable = CodeMatrix.Business.GenericData.GetStpDepartmentHirachy()
        For Each i As DataRow In tbl.Rows

            cCascadingDropDownNameValue.Add( _
                New CascadingDropDownNameValue(i("department_name"), i("department_code")) _
            )

        Next

        Return cCascadingDropDownNameValue.ToArray()

    End Function

    <WebMethod(EnableSession:=True)> _
    Public Function UpdateSession(ByVal UserId As String) As String


        Dim text = String.Empty

        If Not User Is Nothing Then


            ' Execute store to get remain time
            Dim time = CodeMatrix.Utilities.CodeHelper.GetSingleObject( _
                "exec USP_GetUserShowTime @UserId", _
                New SqlParameter() { _
                 New SqlParameter("@UserId", UserId)})


            If time - 420 + 3 > 0 Then

                text = "OUT_OF_TIME"
                ' Comment by Boonyarit
                'FormsAuthentication.SignOut()

            Else

                text = String.Format("วันที่ {0} เวลาที่เข้าใช้งานระบบ {1} นาที", _
                                     DateTime.Now.ToString("dd MMMM yyyy", New CultureInfo("th-TH")), _
                                     time - 420)

            End If

        End If


        Return text


    End Function

    ' Commented by Boonyarit Yingvoragan
    ' Commented date 29/10/2010
    ' Not used
    'Private Shared Function GetStaffCode() As Int32
    '    Return 3
    'End Function


    <WebMethod(EnableSession:=True)> _
    Public Function CheckAndSaveAuthenDepartmentObject(ByVal jdata As String) As String

        Dim JResult
        Dim ctx As DataClassesDataContext = New DataClassesDataContext

        Try

            Dim sl = New JavaScriptSerializer()
            Dim objData = sl.Deserialize(Of AuthDepartmentObject())(jdata)

            If objData.Count() > 0 Then
                For Each i In ctx.stp_auth_departments.Where(Function(f) f.department_code = objData(0).department_code)
                    Throw New Exception("มีการกำหนดสิทธิ์การใช้งานของหน่วยงานนี้ไว้แล้ว")
                Next
            End If

            SaveAuthenDepartmentObject(jdata)

        Catch ex As Exception
            JResult = New With {.Message = ex.Message}
            Return New JavaScriptSerializer().Serialize(JResult)
        Finally
            ctx.Dispose()
        End Try

        JResult = New With {.Message = "success"}
        Return New JavaScriptSerializer().Serialize(JResult)

    End Function

    <WebMethod(EnableSession:=True)> _
    Public Function SaveAuthenDepartmentObject(ByVal jdata As String) As String

        Dim JResult
        Dim ctx As DataClassesDataContext = New DataClassesDataContext

        Try

            Dim sl = New JavaScriptSerializer()
            Dim objData = sl.Deserialize(Of AuthDepartmentObject())(jdata)
            Dim log As String = ""

            ' Commented by Boonyarit Yingvoragan
            ' Commented date 29/10/2010
            ' Not used
            'If objData.Count() > 0 Then
            '    Dim removeObjs = ctx.stp_auth_departments.Where(Function(f) f.department_code = objData(0).department_code)
            '    ctx.stp_auth_departments.DeleteAllOnSubmit(removeObjs)
            'End If

            If objData.Length > 0 Then
                log &= "ผู้ใช้งาน " & HttpContext.Current.Session("staff_no") & " แก้ไขสิทธิการใช้งานหน่วยงาน " & ctx.stp_departments.SingleOrDefault(Function(f) f.department_code = objData(0).department_code).department_name & " "
            End If

            For Each i In objData

                Dim iAuth = New CodeMatrix.Entities.stp_auth_department

                iAuth.auth_department_code = i.auth_department_code
                iAuth.department_code = i.department_code
                iAuth.sub_menu_code = i.sub_menu_code
                iAuth.auth_department_status = 1

                If i.checked = False Then
                    Dim removeObjs = ctx.stp_auth_departments.Where(Function(f) f.auth_department_code = iAuth.auth_department_code)
                    If removeObjs.Count() > 0 Then ctx.stp_auth_departments.DeleteAllOnSubmit(removeObjs)
                    log &= "ลบสิทธิใช้งาน sub_menu_code: " & i.sub_menu_code & ", "
                Else
                    If i.auth_department_code > 0 Then
                        iAuth.staff_code_update = Session("staff_code")
                        iAuth.update_datetime = Now
                        ctx.stp_auth_departments.Attach(iAuth)
                        log &= "ให้สิทธิใช้งาน sub_menu_code: " & i.sub_menu_code & ", "
                    Else
                        iAuth.staff_code_create = Session("staff_code")
                        iAuth.create_datetime = Now
                        ctx.stp_auth_departments.InsertOnSubmit(iAuth)
                        log &= "ให้สิทธิใช้งาน sub_menu_code: " & i.sub_menu_code & ", "
                    End If
                End If

            Next

            ctx.SubmitChanges()
            CodeMatrix.Business.GenericData.WriteLog(log, 10, "U", Session("staff_code"))

        Catch ex As Exception
            JResult = New With {.Message = ex.Message}
            Return New JavaScriptSerializer().Serialize(JResult)
        Finally
            ctx.Dispose()
        End Try

        JResult = New With {.Message = "success"}
        Return New JavaScriptSerializer().Serialize(JResult)

    End Function

    <WebMethod(EnableSession:=True)> _
    Public Function GetAuthenDepartmentObject(ByVal main_system_code As Int32, ByVal department_code As Int32) As String

        Dim ctx As DataClassesDataContext = New DataClassesDataContext()
        Dim dataObject As String = String.Empty
        Try


            Dim cObjMasterType = ctx.master_types _
            .Where(Function(f) f.type_status = 1) _
            .Select(Function(f) New With {f.type_code, f.type_name}) _
            .ToArray()


            '  _
            Dim cObjMainSystem = ctx.stp_main_systems _
            .Where(Function(f) _
                     (f.main_system_code = main_system_code) _
                    And f.main_system_status = 1) _
            .Select(Function(f) New With {f.main_system_code, f.main_system_name}) _
            .ToArray()

            Dim cObjMenuSystem = ctx.stp_menu_systems _
            .Where(Function(f) f.menu_system_status = 1 And cObjMainSystem.Select(Function(k) k.main_system_code).Contains(f.main_system_code)) _
            .Select(Function(f) New With {f.main_system_code, f.menu_system_code, f.menu_system_name}) _
            .ToArray()

            'And cObjMainSystem.Select(Function(k) k.main_system_code).Contains(f.main_system_code) _
            Dim cObjSubMenu = ctx.stp_sub_menus _
            .Where(Function(f) f.sub_menu_status = 1 _
                       And cObjMenuSystem.Select(Function(k) k.menu_system_code).Contains(f.menu_system_code)) _
            .Select(Function(f) New With {f.type_code, f.sub_menu_code, f.sub_menu_name, f.main_system_code, f.menu_system_code}) _
            .ToArray()

            'f.department_code = department_code
            Dim cObjAuthDepartment = ctx.stp_auth_departments _
            .Where(Function(f) f.auth_department_status = 1 And f.department_code = department_code) _
            .Select(Function(f) New With {f.auth_department_code, f.department_code, f.sub_menu_code}) _
            .ToArray()



            Dim outObject = New With {.MasterTypes = cObjMasterType, _
                                      .MainSystems = cObjMainSystem, _
                                      .MenuSystems = cObjMenuSystem, _
                                      .SubMenus = cObjSubMenu, _
                                      .AuthDepartments = cObjAuthDepartment, _
                                      .Department_code = department_code, _
                                      .Main_system_code = main_system_code _
                                      }

            Dim serial As JavaScriptSerializer = New JavaScriptSerializer()
            dataObject = serial.Serialize(outObject)

        Catch ex As Exception

            dataObject = "-1"

        Finally

            ctx.Dispose()

        End Try


        Return dataObject

    End Function


    <WebMethod(EnableSession:=True)> _
    Public Function GetAuthenGroupObject(ByVal department_code As Int32, ByVal group_user_code As Int32) As String

        Dim ctx As DataClassesDataContext = New DataClassesDataContext()
        Dim dataObject As String = String.Empty
        Try


            Dim cObjMasterType = ctx.master_types _
            .Where(Function(f) f.type_status = 1) _
            .Select(Function(f) New With {f.type_code, f.type_name}) _
            .ToArray()

            '.Where(Function(f) f.main_system_type = 1) _
            Dim cObjMainSystem = ctx.stp_main_systems _
            .Select(Function(f) New With {f.main_system_code, f.main_system_name}) _
            .ToArray()


            Dim cObjMenuSystem = ctx.stp_menu_systems _
            .Where(Function(f) f.menu_system_status = 1 And cObjMainSystem.Select(Function(k) k.main_system_code).Contains(f.main_system_code)) _
            .Select(Function(f) New With {f.main_system_code, f.menu_system_code, f.menu_system_name}) _
            .ToArray()

            Dim cObjSubMenu = ctx.stp_sub_menus _
            .Where(Function(f) f.sub_menu_status = 1 _
                       And cObjMenuSystem.Select(Function(k) k.menu_system_code).Contains(f.menu_system_code)) _
            .Select(Function(f) New With {f.type_code, f.sub_menu_code, f.sub_menu_name, f.main_system_code, f.menu_system_code}) _
            .ToArray()






            Dim cAuthenDeptCode = ctx.stp_auth_departments _
            .Where(Function(f) f.department_code = department_code And f.auth_department_status = 1) _
            .Select(Function(f) f.auth_department_code) _
            .ToArray()

            Dim cPermitSystem = cObjSubMenu.Select(Function(f) f.main_system_code).Distinct().ToArray()

            cObjMainSystem = cObjMainSystem.Where(Function(f) cPermitSystem.Contains(f.main_system_code)).ToArray()


            ' ============================================================================
            ' Group Authen objects
            ' ============================================================================
            Dim cAuthenDepartment = ctx.USP_GetAuthGroupObjects(department_code).ToArray()

            For Each i In cAuthenDepartment


                If i.group_code <> group_user_code Then

                    i.group_code = 0
                    i.auth_group_code = 0

                End If


            Next


            '_.Where(Function(f) f.group_code = group_user_code)


            Dim outObject = New With {.MasterTypes = cObjMasterType, _
                                      .MainSystems = cObjMainSystem, _
                                      .MenuSystems = cObjMenuSystem, _
                                      .SubMenus = cObjSubMenu, _
                                      .AuthDepartments = cAuthenDepartment, _
                                      .Department_code = department_code, _
                                      .Main_system_code = 0, _
                                      .AuthenDeptCodes = cAuthenDeptCode, _
                                      .Group_code = group_user_code _
                                      }

            Dim serial As JavaScriptSerializer = New JavaScriptSerializer()
            dataObject = serial.Serialize(outObject)

        Catch ex As Exception

            dataObject = "-1"

        Finally

            ctx.Dispose()

        End Try


        Return dataObject

    End Function

    <WebMethod(EnableSession:=True)> _
    Public Function CheckAndSaveAuthenGroupObject(ByVal jdata As String) As String

        Dim JResult
        Dim ctx As DataClassesDataContext = New DataClassesDataContext
        Try

            Dim sl = New JavaScriptSerializer()
            Dim objData = sl.Deserialize(Of AuthGroupObject())(jdata)

            If objData.Count() > 0 Then
                Dim group_code = ctx.stp_auth_groups.Where(Function(f) f.group_code = objData(0).group_code)
                If group_code.Count() > 0 Then Throw New Exception("มีการกำหนดสิทธิ์การใช้งานของกลุ่มนี้ไว้แล้ว")
            End If

            SaveAuthenGroupObject(jdata)

        Catch ex As Exception
            JResult = New With {.Message = ex.Message}
            Return New JavaScriptSerializer().Serialize(JResult)
        Finally
            ctx.Dispose()
        End Try

        JResult = New With {.Message = "success"}
        Return New JavaScriptSerializer().Serialize(JResult)

    End Function

    <WebMethod(EnableSession:=True)> _
    Public Function SaveAuthenGroupObject(ByVal jdata As String) As String

        Dim JResult
        Dim ctx As DataClassesDataContext = New DataClassesDataContext
        Try

            Dim sl = New JavaScriptSerializer()
            Dim objData = sl.Deserialize(Of AuthGroupObject())(jdata)
            Dim log As String = ""

            ' Commented by Boonyarit Yingvoragan
            ' Commented date 29/10/2010
            ' Not used
            'If objData.Where(Function(f) f.group_code <> 0 And f.auth_dep_code <> 0).Count() > 0 Then
            '    Dim group_code_to_delete = objData.Where(Function(f) f.group_code <> 0 And f.auth_dep_code <> 0)(0).group_code
            '    Dim removeObjs = ctx.stp_auth_groups.Where(Function(f) f.group_code = group_code_to_delete)
            '    ctx.stp_auth_groups.DeleteAllOnSubmit(removeObjs)
            'End If

            If objData.Length > 0 Then
                log &= "ผู้ใช้งาน " & HttpContext.Current.Session("staff_no") & " แก้ไขสิทธิการใช้งานกลุ่มผู้ใช้งาน " & ctx.group_users.SingleOrDefault(Function(f) f.group_user_code = objData(0).group_code).group_user_name & " "
            End If

            For Each i In objData
                Dim iAuth = New CodeMatrix.Entities.stp_auth_group

                iAuth.auth_group_code = i.auth_group_code
                iAuth.auth_dep_code = i.auth_dep_code
                iAuth.group_code = i.group_code
                iAuth.auth_group_status = 1

                If i.checked = False Then
                    Dim removeObjs = ctx.stp_auth_groups.Where(Function(f) f.auth_group_code = iAuth.auth_group_code)
                    If removeObjs.Count() > 0 Then ctx.stp_auth_groups.DeleteAllOnSubmit(removeObjs)
                    log &= "ลบสิทธิใช้งาน auth_dep_code: " & i.auth_dep_code & ", "
                Else
                    If i.auth_group_code > 0 Then
                        iAuth.staff_code_update = Session("staff_code")
                        iAuth.update_datetime = Now
                        ctx.stp_auth_groups.Attach(iAuth)
                        log &= "ให้สิทธิใช้งาน auth_dep_code: " & i.auth_dep_code & ", "
                    Else
                        iAuth.staff_code_create = Session("staff_code")
                        iAuth.create_datetime = Now
                        ctx.stp_auth_groups.InsertOnSubmit(iAuth)
                        log &= "ให้สิทธิใช้งาน auth_dep_code: " & i.auth_dep_code & ", "
                    End If
                End If
            Next

            ctx.SubmitChanges()
            CodeMatrix.Business.GenericData.WriteLog(log, 14, "U", Session("staff_code"))

        Catch ex As Exception
            JResult = New With {.Message = ex.Message}
            Return New JavaScriptSerializer().Serialize(JResult)
        Finally
            ctx.Dispose()
        End Try

        JResult = New With {.Message = "success"}
        Return New JavaScriptSerializer().Serialize(JResult)

    End Function


    <WebMethod(EnableSession:=True)> _
        Public Function GetAuthenStaffObject(ByVal department_code As Int32, ByVal group_code As Integer, ByVal Staff_code As Int32) As String

        Dim ctx As DataClassesDataContext = New DataClassesDataContext()
        Dim dataObject As String = String.Empty
        Try


            Dim cObjMasterType = ctx.master_types _
            .Where(Function(f) f.type_status = 1) _
            .Select(Function(f) New With {f.type_code, f.type_name}) _
            .ToArray()


            Dim cObjMainSystem = ctx.stp_main_systems _
            .Where(Function(f) f.main_system_status = 1) _
            .Select(Function(f) New With {f.main_system_code, f.main_system_name}) _
            .ToArray()


            Dim cObjMenuSystem = ctx.stp_menu_systems _
            .Where(Function(f) f.menu_system_status = 1 And cObjMainSystem.Select(Function(k) k.main_system_code).Contains(f.main_system_code)) _
            .Select(Function(f) New With {f.main_system_code, f.menu_system_code, f.menu_system_name}) _
            .ToArray()

            Dim cObjSubMenu = ctx.stp_sub_menus _
            .Where(Function(f) f.sub_menu_status = 1 _
                       And cObjMenuSystem.Select(Function(k) k.menu_system_code).Contains(f.menu_system_code)) _
            .Select(Function(f) New With {f.type_code, f.sub_menu_code, f.sub_menu_name, f.main_system_code, f.menu_system_code}) _
            .ToArray()

            'Dim cAuthenDeptCode = ctx.stp_auth_departments _
            '.Where(Function(f) f.department_code = department_code And f.auth_department_status = 1) _
            '.Select(Function(f) f.auth_department_code) _
            '.ToArray()

            Dim cAuthenDeptCode = ctx.ExecuteQuery(Of Integer)( _
            "	select  dept.auth_department_code  " & _
    "" & _
 "from		stp_auth_department as dept " & _
 "left join	stp_auth_group as gp on dept.auth_department_code = gp.auth_dep_code " & _
 "where	dept.department_code = {0} " & _
   "and auth_department_status = 1 and {1} in (0,group_code)", department_code, group_code)


            cAuthenDeptCode = cAuthenDeptCode.ToArray()


            Dim cPermitSubmenu = ctx.ExecuteQuery(Of Integer)( _
            "	select  dept.sub_menu_code  " & _
    "" & _
 "from		stp_auth_department as dept " & _
 "left join	stp_auth_group as gp on dept.auth_department_code = gp.auth_dep_code " & _
 "where	dept.department_code = {0} " & _
   "and auth_department_status = 1 and {1} in (0,group_code)", department_code, group_code)

            cPermitSubmenu = cPermitSubmenu.ToArray()


            cObjSubMenu = cObjSubMenu.Where(Function(f) cPermitSubmenu.Contains(f.sub_menu_code)).ToArray()

            Dim cPermitSystem = cObjSubMenu.Select(Function(f) f.main_system_code).Distinct().ToArray()

            cObjMainSystem = cObjMainSystem.Where(Function(f) cPermitSystem.Contains(f.main_system_code)).ToArray()

            ' =============================================================================
            ' Staff Authen objects
            ' =============================================================================
            Dim cAuthenDepartment = ctx.USP_GetAuthStaffObjects(department_code).ToArray()
            For Each i In cAuthenDepartment

                If i.staff_code <> Staff_code Then

                    i.staff_code = 0
                    i.auth_staff_code = 0

                End If

            Next



            Dim outObject = New With {.MasterTypes = cObjMasterType, _
                                      .MainSystems = cObjMainSystem, _
                                      .MenuSystems = cObjMenuSystem, _
                                      .SubMenus = cObjSubMenu, _
                                      .AuthDepartments = cAuthenDepartment, _
                                      .Department_code = department_code, _
                                      .Main_system_code = 0, _
                                      .AuthenDeptCodes = cAuthenDeptCode, _
                                      .Staff_code = Staff_code _
                                      }

            Dim serial As JavaScriptSerializer = New JavaScriptSerializer()
            dataObject = serial.Serialize(outObject)

        Catch ex As Exception

            dataObject = "-1"

        Finally

            ctx.Dispose()

        End Try


        Return dataObject

    End Function

    <WebMethod(EnableSession:=True)> _
    Public Function CheckAndSaveAuthenStaffObject(ByVal jdata As String) As String

        Dim JResult
        Dim ctx As DataClassesDataContext = New DataClassesDataContext
        Try

            Dim sl = New JavaScriptSerializer()
            Dim objData = sl.Deserialize(Of AuthStaffObject())(jdata)

            If objData.Count() > 0 Then
                Dim staff_code = ctx.stp_auth_staffs.Where(Function(f) f.staff_code = objData(0).staff_code)
                If staff_code.Count() > 0 Then Throw New Exception("มีการกำหนดสิทธิ์การใช้งานของผู้ใช้งานนี้ไว้แล้ว")
            End If

            SaveAuthenStaffObject(jdata)

        Catch ex As Exception
            JResult = New With {.Message = ex.Message}
            Return New JavaScriptSerializer().Serialize(JResult)
        Finally
            ctx.Dispose()
        End Try

        JResult = New With {.Message = "success"}
        Return New JavaScriptSerializer().Serialize(JResult)

    End Function

    <WebMethod(EnableSession:=True)> _
    Public Function SaveAuthenStaffObject(ByVal jdata As String) As String

        Dim JResult
        Dim ctx As DataClassesDataContext = New DataClassesDataContext
        Try

            Dim sl = New JavaScriptSerializer()
            Dim objData = sl.Deserialize(Of AuthStaffObject())(jdata)
            Dim log As String = ""

            ' Commented by Boonyarit Yingvoragan
            ' Commented date 31/10/2010
            ' Not used
            'If objData.Where(Function(f) f.staff_code <> 0 And f.auth_dep_code <> 0).Count() > 0 Then
            '    Dim staff_code_to_delete = objData.Where(Function(f) f.staff_code <> 0 And f.auth_dep_code <> 0)(0).staff_code
            '    Dim removeObjs = ctx.stp_auth_staffs.Where(Function(f) f.staff_code = staff_code_to_delete)
            '    ctx.stp_auth_staffs.DeleteAllOnSubmit(removeObjs)
            'End If

            If objData.Length > 0 Then
                log &= "ผู้ใช้งาน " & HttpContext.Current.Session("staff_no") & " แก้ไขสิทธิการใช้งานผู้ใช้งาน " & ctx.staffs.SingleOrDefault(Function(f) f.staff_code = objData(0).staff_code).staff_no & " "
            End If

            For Each i In objData
                Dim iAuth = New CodeMatrix.Entities.stp_auth_staff

                iAuth.auth_staff_code = i.auth_staff_code
                iAuth.auth_dep_code = i.auth_dep_code
                iAuth.staff_code = i.staff_code
                iAuth.auth_staff_status = 1

                If i.checked = False Then
                    Dim removeObjs = ctx.stp_auth_staffs.Where(Function(f) f.auth_staff_code = iAuth.auth_staff_code)
                    If removeObjs.Count() > 0 Then ctx.stp_auth_staffs.DeleteAllOnSubmit(removeObjs)
                    log &= "ลบสิทธิใช้งาน auth_dep_code: " & i.auth_dep_code & ", "
                Else
                    If i.auth_staff_code > 0 Then
                        iAuth.staff_code_update = Session("staff_code")
                        iAuth.update_datetime = Now
                        ctx.stp_auth_staffs.Attach(iAuth)
                        log &= "ให้สิทธิใช้งาน auth_dep_code: " & i.auth_dep_code & ", "
                    Else
                        iAuth.staff_code_create = Session("staff_code")
                        iAuth.create_datetime = Now
                        ctx.stp_auth_staffs.InsertOnSubmit(iAuth)
                        log &= "ให้สิทธิใช้งาน auth_dep_code: " & i.auth_dep_code & ", "
                    End If
                End If
            Next

            ctx.SubmitChanges()
            CodeMatrix.Business.GenericData.WriteLog(log, 11, "U", Session("staff_code"))

        Catch ex As Exception
            JResult = New With {.Message = ex.Message}
            Return New JavaScriptSerializer().Serialize(JResult)
        Finally
            ctx.Dispose()
        End Try

        JResult = New With {.Message = "success"}
        Return New JavaScriptSerializer().Serialize(JResult)

    End Function

    Public Structure JSResponse
        Public Result As String
    End Structure

    <WebMethod(EnableSession:=True)> _
    Function checkDuplicateDepartmentNo(ByVal department_number As String) As String
        Dim ctx As DataClassesDataContext = New DataClassesDataContext
        Dim departmentNumber As String = department_number
        Dim js As New JavaScriptSerializer()
        Dim res As New JSResponse
        Dim count = ctx.stp_departments.Count(Function(f) f.department_number = departmentNumber)

        If count > 0 Then
            res.Result = "false"
        Else
            res.Result = "true"
        End If
        Return js.Serialize(res)
    End Function

    <WebMethod(EnableSession:=True)> _
    Function checkDuplicateStaffNo(ByVal staff_no As String) As String
        Dim ctx As DataClassesDataContext = New DataClassesDataContext
        Dim staffNumber As String = staff_no
        Dim js As New JavaScriptSerializer()
        Dim res As New JSResponse
        Dim count = ctx.staffs.Count(Function(f) f.staff_no = staffNumber)

        If count > 0 Then
            res.Result = "false"
        Else
            res.Result = "true"
        End If
        Return js.Serialize(res)
    End Function

    <WebMethod(EnableSession:=True)> _
    Function ResetPassword(ByVal staff_code As Int32) As String
        Dim ctx As DataClassesDataContext = New DataClassesDataContext
        Dim js As New JavaScriptSerializer()
        Dim res As New JSResponse
        Dim saltValue As String = System.Guid.NewGuid().ToString().Replace("-", "").Substring(0, 16)
        Try
            Dim password As String = CodeMatrix.Business.GenericData.GetNewPassword(saltValue)
            CodeMatrix.Utilities.CodeHelper.ExecuteNonQuery( _
            "UPDATE staff SET staff_password = @staff_password, staff_password_salt = @staff_password_salt, staff_fail_login = 0 WHERE staff_code = @staff_code", _
            New SqlParameter("@staff_code", staff_code), _
            New SqlParameter("@staff_password", password), _
            New SqlParameter("@staff_password_salt", saltValue))

            Dim staff_no = ctx.staffs.SingleOrDefault(Function(f) f.staff_code = staff_code).staff_no
            CodeMatrix.Business.GenericData.WriteLog("ผู้ใช้งาน " & HttpContext.Current.Session("staff_no") & " เปลี่ยนรหัสผ่านผู้ใช้งาน " & staff_no & " เป็นค่าเริ่มต้นเรียบร้อยแล้ว", 13, "U", staff_code)
            res.Result = "true"
        Catch ex As Exception
            res.Result = ex.Message
        End Try
        Return js.Serialize(res)
    End Function
#Region "Kim Assign Method for return Destination URL"
    <WebMethod(EnableSession:=True)> _
 Public Function GetDestination(ByVal sub_menu_code As Int32) As String

        Dim ctx As DataClassesDataContext = New DataClassesDataContext()
        Dim dataObject As String = String.Empty
        Try


            Dim cObjSubMenuURL = ctx.stp_sub_menus _
            .Where(Function(f) f.sub_menu_code = sub_menu_code) _
            .Select(Function(f) New With {f.sub_menu_url}) _
            .ToArray()




            Dim outObject = New With {.StpSubMenu = cObjSubMenuURL}

            Dim serial As JavaScriptSerializer = New JavaScriptSerializer()
            dataObject = serial.Serialize(outObject)

        Catch ex As Exception

            dataObject = "-1"

        Finally

            ctx.Dispose()

        End Try


        Return dataObject

    End Function
#End Region

End Class
